<template>
  <div class="order-review">
    <el-container>
      <el-header class="page-header">
        <div class="page-title">
          <el-button @click="goBack" icon="ArrowLeft" text>返回</el-button>
          <span>订单评价</span>
        </div>
      </el-header>
      
      <el-main>
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="!order" class="empty-container">
          <el-empty description="订单不存在" />
        </div>
        
        <div v-else class="review-content">
          <!-- 订单信息 -->
          <el-card class="order-info-card">
            <template #header>
              <span>订单信息</span>
            </template>
            <div class="order-info">
              <p><strong>订单编号：</strong>{{ getOrderNumber(order) }}</p>
              <p><strong>下单时间：</strong>{{ formatDate(order.createdAt) }}</p>
              <p><strong>订单状态：</strong>
                <el-tag :type="getStatusType(getOrderStatus(order))" size="small">
                  {{ getStatusText(getOrderStatus(order)) }}
                </el-tag>
              </p>
            </div>
          </el-card>

          <!-- 商品列表 -->
          <el-card class="products-card">
            <template #header>
              <span>商品列表</span>
            </template>
            <div class="products-list">
              <div 
                v-for="item in getOrderItems(order)" 
                :key="item.itemId" 
                class="product-item"
              >
                <div class="product-info">
                  <img :src="item.productImage" :alt="item.productName" class="product-image" />
                  <div class="product-details">
                    <h4>{{ item.productName }}</h4>
                    <p class="product-spec">{{ item.productSku || item.sku || '默认规格' }}</p>
                    <p class="product-price">¥{{ item.productPrice || item.price }} × {{ item.quantity }}</p>
                  </div>
                </div>
                
                <!-- 评价表单 -->
                <div class="review-form" v-if="!item.hasReview">
                  <div class="rating-section">
                    <span class="rating-label">评分：</span>
                    <el-rate 
                      v-model="item.rating" 
                      :max="5" 
                      show-text 
                      :texts="['很差', '差', '一般', '好', '很好']"
                    />
                  </div>
                  <div class="comment-section">
                    <el-input
                      v-model="item.comment"
                      type="textarea"
                      :rows="3"
                      placeholder="请分享您的使用体验..."
                      maxlength="500"
                      show-word-limit
                    />
                  </div>
                  <el-button 
                    type="primary" 
                    @click="submitReview(item)"
                    :loading="item.submitting"
                  >
                    提交评价
                  </el-button>
                </div>
                
                <!-- 已评价显示 -->
                <div v-else class="reviewed-info">
                  <el-tag type="success" size="small">已评价</el-tag>
                  <div class="rating-display">
                    <el-rate :value="item.rating" disabled />
                  </div>
                  <p class="comment-display">{{ item.comment }}</p>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { orderService } from '@/api'
import { reviewService } from '@/api/reviewService'
import type { OrderStatus } from '@/types/order'

// 统一的订单项类型，包含评价相关字段
type UnifiedOrderItem = {
  itemId: number
  orderId: number
  productId?: number
  shoeId?: number
  productName: string
  productImage: string
  quantity: number
  price?: number
  productPrice?: number
  sku?: string
  productSku?: string
  subtotal?: number
  totalPrice?: number
  // 评价相关字段
  rating: number
  comment: string
  hasReview: boolean
  submitting: boolean
}

// 兼容后端数据的订单类型
interface BackendOrder {
  orderId: number
  orderSn: string
  userId: number
  totalAmount: number
  payAmount: number
  status: number
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  remark: string
  createdAt: string
  updatedAt: string
  orderItems: Array<{
    itemId: number
    orderId: number
    shoeId: number
    productSku: string
    productName: string
    productImage: string
    productPrice: number
    quantity: number
    totalPrice: number
  }>
  statusDesc: string
}

// 兼容前端数据的订单类型
interface FrontendOrder {
  orderId: number
  orderNumber: string
  userId: number
  addressId: number
  productTotal: number
  shippingFee: number
  finalTotal: number
  status: OrderStatus
  paymentStatus: string
  paymentMethod: string
  shippingMethod: string
  remark?: string
  createdAt: string
  updatedAt: string
  items: Array<{
    orderItemId: number
    orderId: number
    productId: number
    productName: string
    productImage: string
    quantity: number
    price: number
    sku?: string
    subtotal: number
  }>
  address?: unknown
}

// 联合类型，兼容前端和后端的数据结构
type CompatibleOrder = FrontendOrder | BackendOrder

const route = useRoute()
const router = useRouter()

// 响应式数据
const order = ref<CompatibleOrder | null>(null)
const loading = ref(false)

// 类型守卫函数
function isBackendOrder(order: CompatibleOrder): order is BackendOrder {
  return 'orderSn' in order && 'orderItems' in order
}

// 获取订单编号
const getOrderNumber = (order: CompatibleOrder) => {
  if (isBackendOrder(order)) {
    return order.orderSn
  }
  return order.orderNumber
}

// 获取订单项列表
const getOrderItems = (order: CompatibleOrder): UnifiedOrderItem[] => {
  if (isBackendOrder(order)) {
    return order.orderItems.map(item => ({
      itemId: item.itemId,
      orderId: item.orderId,
      shoeId: item.shoeId,
      productName: item.productName,
      productImage: item.productImage,
      quantity: item.quantity,
      productPrice: item.productPrice,
      productSku: item.productSku,
      totalPrice: item.totalPrice,
      // 初始化评价字段
      rating: 5,
      comment: '',
      hasReview: false,
      submitting: false
    }))
  }
  return order.items.map(item => ({
    itemId: item.orderItemId,
    orderId: item.orderId,
    productId: item.productId,
    productName: item.productName,
    productImage: item.productImage,
    quantity: item.quantity,
    price: item.price,
    sku: item.sku,
    subtotal: item.subtotal,
    // 初始化评价字段
    rating: 5,
    comment: '',
    hasReview: false,
    submitting: false
  }))
}

// 获取订单状态
const getOrderStatus = (order: CompatibleOrder) => {
  if (isBackendOrder(order)) {
    return order.status
  }
  return order.status
}

// 方法
const fetchOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) return

  loading.value = true
  try {
    const response = await orderService.getOrderDetail(Number(orderId))
    order.value = response.data.data
    
    // 为每个订单项添加评价相关字段
    const items = getOrderItems(order.value)
    if (items) {
      // 这些字段在 getOrderItems 中已经初始化，这里不需要重复设置
    }
    
    console.log('订单详情加载成功:', {
      orderId: order.value?.orderId,
      orderNumber: getOrderNumber(order.value),
      status: getOrderStatus(order.value),
      itemsCount: getOrderItems(order.value)?.length
    })
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
    setTimeout(() => {
      router.push('/orders')
    }, 2000)
  } finally {
    loading.value = false
  }
}

const getStatusType = (status: number | OrderStatus): 'warning' | 'info' | 'primary' | 'success' | 'danger' => {
  // 如果是数字状态（后端格式），转换为对应的类型
  if (typeof status === 'number') {
    const statusMap: Record<number, 'warning' | 'info' | 'primary' | 'success' | 'danger'> = {
      0: 'warning',  // 待付款
      1: 'info',     // 待发货
      2: 'primary',  // 运输中
      3: 'success',  // 已完成
      4: 'danger',   // 已取消
      5: 'warning',  // 申请退货
      6: 'info',     // 已退货
    }
    return statusMap[status] || 'info'
  }
  
  // 如果是字符串状态（前端格式），转换为对应的类型
  const statusMap: Record<OrderStatus, 'warning' | 'info' | 'primary' | 'success' | 'danger'> = {
    'PENDING_PAYMENT': 'warning',
    'PAID': 'info',
    'SHIPPED': 'primary',
    'DELIVERED': 'success',
    'COMPLETED': 'success',
    'CANCELLED': 'danger',
    'EXPIRED': 'info',
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: number | OrderStatus): string => {
  // 如果是数字状态（后端格式），转换为对应的文本
  if (typeof status === 'number') {
    const statusMap: Record<number, string> = {
      0: '待付款',
      1: '待发货',
      2: '运输中',
      3: '已完成',
      4: '已取消',
      5: '申请退货',
      6: '已退货',
    }
    return statusMap[status] || '未知状态'
  }
  
  // 如果是字符串状态（前端格式），转换为对应的文本
  const statusMap: Record<OrderStatus, string> = {
    'PENDING_PAYMENT': '待付款',
    'PAID': '待发货',
    'SHIPPED': '运输中',
    'DELIVERED': '已送达',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消',
    'EXPIRED': '已过期',
  }
  return statusMap[status] || '未知状态'
}

const formatDate = (date: string | Date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const submitReview = async (item: UnifiedOrderItem) => {
  if (!item.rating || item.rating < 1) {
    ElMessage.warning('请选择评分')
    return
  }
  
  if (!item.comment || item.comment.trim().length < 5) {
    ElMessage.warning('评价内容至少5个字符')
    return
  }

  try {
    item.submitting = true
    
    // 调用评价API
    await reviewService.addReview({
      orderItemId: item.itemId,
      rating: item.rating,
      comment: item.comment.trim()
    })
    
    ElMessage.success('评价提交成功')
    item.hasReview = true
    
    // 刷新订单详情
    fetchOrderDetail()
  } catch (error: unknown) {
    if (error !== 'cancel') {
      console.error('评价提交失败:', error)
      const errorMessage = error instanceof Error ? error.message : '评价提交失败'
      ElMessage.error(errorMessage)
    }
  } finally {
    item.submitting = false
  }
}

const goBack = () => {
  router.back()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-review {
  min-height: calc(100vh - 64px);
  background-color: #f8fafc;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  background: white;
  border-bottom: 1px solid #e9ecef;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.review-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-info-card,
.products-card {
  margin-bottom: 0;
}

.order-info p {
  margin: 8px 0;
  line-height: 1.6;
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.product-item {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 20px;
  background: #fafbfc;
}

.product-info {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.product-details h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
}

.product-spec {
  margin: 4px 0;
  color: #606266;
  font-size: 14px;
}

.product-price {
  margin: 4px 0;
  color: #e6a23c;
  font-weight: 500;
}

.review-form {
  border-top: 1px solid #e9ecef;
  padding-top: 20px;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.rating-label {
  font-weight: 500;
  color: #303133;
}

.comment-section {
  margin-bottom: 16px;
}

.reviewed-info {
  border-top: 1px solid #e9ecef;
  padding-top: 20px;
  text-align: center;
}

.rating-display {
  margin: 12px 0;
}

.comment-display {
  margin: 8px 0;
  color: #606266;
  font-style: italic;
}
</style>
